﻿using Bigway.Common.Models.DtoModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;

namespace Bigway.Common.Filters;

public class CustomExceptionFilter(ILogger<CustomExceptionFilter> logger): IExceptionFilter
{
    public void OnException(ExceptionContext context)
    {
        var exception = context.Exception;
        const string message = "An unhandled exception occurred on the server.";
        logger.LogError(exception, message);

        context.Result = new JsonResult(
            new NoDataResponseDto()
            {
                Error = new ErrorDto()
                {
                    Code = ErrorCode.InternalError,
                    Message = message + exception,
                    UserMessage = "服务器发生未知错误. 请联系后端开发者."
                }
            }
        )
        {
            StatusCode = 200
        };

        context.ExceptionHandled = true;
    }
}